package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.TruncateSize;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class GoodServiceAspect {

    /**
     * 切点前置通知
     */
    @Before("execution(* com.ruoyi.goods.service..*.updateTGoodsInfo(..))")
    //@Before("execution(* com.ruoyi.goods.domain..*.updateTGoodsInfo(..))")
    public void before() {
        System.out.println("前置通知");
    }

    /**
     * 切点后置通知
     */
    @After("execution(* com.ruoyi.goods.service..*.updateTGoodsInfo(..))")
    public void after() {
        System.out.println("后置通知");
    }

    /**
     * 切点环绕通知
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("execution(* com.ruoyi.goods.service..*.updateTGoodsInfo(..))")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("====环绕开始====");
        // 切面中获取到调用方法名
        String methodName = proceedingJoinPoint.getSignature().getName();
        // 切面中获取到调用方法的参数
        Object[] args = proceedingJoinPoint.getArgs();

        // 执行调用方法
        Object result = proceedingJoinPoint.proceed();

        System.out.println("方法名:" + methodName);
        System.out.println("方法参数:" + args.toString());

        System.out.println("====环绕结束====");

        return result;
    }

    /**
     * 切点后置通知返回值
     *
     * @param joinPoint
     * @param result
     */
    @AfterReturning(pointcut = "execution(* com.ruoyi.goods.service..*.*(..))", returning = "result")
    public void afterReturning(JoinPoint joinPoint, String result) {
        System.out.println("后置通知返回值:" + result);
    }

    /**
     * 切点后置通知异常返回
     *
     * @param joinPoint
     * @param exception
     */
    @AfterThrowing(pointcut = "execution(* com.ruoyi.goods.service..*.updateTGoodsInfo(..))",throwing = "exception")
    public void afterThrowing(JoinPoint joinPoint, Exception exception) {
        System.out.println("后置异常返回:" + exception.getMessage());
    }

    @Aspect
    @Component
    public static class TruncateSizeAspect {

        @Around("execution(* set*(..)) && args(value) && @annotation(truncateSize)")
        public Object around(ProceedingJoinPoint joinPoint, String value, TruncateSize truncateSize) throws Throwable {
            if (value != null && value.length() > truncateSize.max()) {
                value = value.substring(0, truncateSize.max());
            }
            return joinPoint.proceed(new Object[]{value});
        }
    }
}
